/*
 * 
 * Document GeneratePdfServlet.java
 * Description: Generate a Pdf document from the confirmation.jsp page
 */
package jhu.bookstore;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.VerticalPositionMark;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.servlet.http.HttpSession;



public class GeneratePdfServlet extends HttpServlet {
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         try {
             
            HttpSession session = request.getSession();
            // Get books from cart
            ArrayList<Book> cart = (ArrayList<Book>) session.getAttribute("confirmation_cart");
            if (cart == null || cart.isEmpty()) {
                 return;
            }
            NumberFormat formater = new DecimalFormat("$#.00");
            
            // step 1
            Document document = new Document();
            // step 2
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            // step 3
            document.open();
            String relativeWebPath = "/img/header_logo.gif";
            String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
            Image logo = Image.getInstance(absoluteDiskPath);
            document.add(logo);
            document.addTitle("JOHN HOPKINS UNIVERSITY BOOKSTORE");
            document.add(new Paragraph("\n\nThe following order was placed: \n\n "));
            
            Chunk tab = new Chunk(new VerticalPositionMark());
            
            com.itextpdf.text.List list = new com.itextpdf.text.List(List.ORDERED);
            list.setIndentationLeft(36);
            list.setIndentationRight(36);
            
            /*ListItem headItem = new ListItem();
            headItem.add("Book Title");
            headItem.add(tab);
            headItem.add("Price");
            list.add(headItem);*/
            double total = 0.0;
            for(Book b : cart) {
                ListItem p = new ListItem();
                p.add(b.getBookName());
                p.add(tab);
                p.add(formater.format(b.getPrice()));
                total += b.getPrice();
                list.add(p);
            }
            document.add(list);
            document.add( new Paragraph("\n\nTotal: " + formater.format(total)));
            // step 5
            document.close();
 
            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();
        }
        catch(DocumentException e) {
            throw new IOException(e.getMessage());
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Servlet generates a PDF for printing";
    }// </editor-fold>
}
